package com.richard.home.viewModel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.richard.base.ui.BaseViewModel
import com.richard.base.net.bean.KsResult
import com.richard.home.model.bean.PoetryWord
import com.richard.home.model.repository.HomeRepositoryImpl
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 ***************************************
 * 项目名称:Giggle
 * @Author wuzhiguo
 * 邮箱：wuzhiguo@ksjgs.com
 * 创建时间: 2020-02-06     16:46
 * 用途:
 ***************************************
 */

class HomeRecViewModelImpl(private val homeRepository: HomeRepositoryImpl) : HomeRecViewModel, BaseViewModel(){

    private val _uiState = MutableLiveData<HomeRecModel>()

    val uiState : LiveData<HomeRecModel> get() = _uiState


    /**
     * 获取推荐图片
     */
    override fun getHomeRecPoetry(pageSize : Int) {
        viewModelScope.launch(Dispatchers.Default){
            val ksResult = homeRepository.getHomeRecPoetry(pageSize)
            withContext(Dispatchers.Main) {
                if (ksResult is KsResult.Success<MutableList<PoetryWord>>) {
                    val uiModel =
                            HomeRecModel(
                                    showLoading = false,
                                    showError = null,
                                    courseInfo = ksResult.data
                            )
                    _uiState.value = uiModel
                } else if (ksResult is KsResult.Error){
                    val uiModel =
                            HomeRecModel(
                                    showLoading = false,
                                    showError = "网络异常",
                                    courseInfo = null
                            )
                    _uiState.value = uiModel
                }
            }
        }
    }


    data class HomeRecModel(
            val showLoading : Boolean,
            val showError: String?,
            val courseInfo: MutableList<PoetryWord>?
    )
}